import './DictManager.css'
import { Button, Form, Input, Modal, Select, Space, Table, message, Tag, Popconfirm } from 'antd'
import { useEffect, useState } from 'react'
import { addDict, deleteDict, getCategories, getPromptList, updateDict } from '../../api/dict'
import { PlusOutlined, SearchOutlined, ReloadOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons'

export default function DictManager() {
    const [data, setData] = useState([])
    const [loading, setLoading] = useState(false)
    const [searchParams, setSearchParams] = useState({})
    const [isModalOpen, setIsModalOpen] = useState(false)
    const [currentDict, setCurrentDict] = useState(null)
    const [categories, setCategories] = useState([])
    const [form] = Form.useForm()
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
    })

    const columns = [
        {
            title: 'ID',
            dataIndex: 'id',
            key: 'id',
        },
        {
            title: '模板名称',
            dataIndex: 'title',
            key: 'title',
        },
        {
            title: '分类',
            dataIndex: 'category',
            key: 'category',
            render: (category) => (
                <Tag className="dict-category-tag">{category}</Tag>
            ),
        },
        {
            title: '标签',
            dataIndex: 'tags',
            key: 'tags',
            render: (tags) => (
                <div className="dict-tags">
                    {Array.isArray(tags) ? tags.map((tag, index) => (
                        <Tag key={index} color="blue">{tag}</Tag>
                    )) : (
                        typeof tags === 'string' ?
                        tags.split(',').map((tag, index) => (
                            <Tag key={index} color="blue">{tag.trim()}</Tag>
                        )) : null
                    )}
                </div>
            ),
        },
        {
            title: '内容预览',
            dataIndex: 'content',
            key: 'content',
            render: (content) => (
                <div className="dict-content-preview" title={content}>
                    {content}
                </div>
            ),
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record) => (
                <Space size="middle">
                    <Button
                        type="primary"
                        size="small"
                        icon={<EditOutlined />}
                        onClick={() => showModal(record)}
                    >
                        编辑
                    </Button>
                    <Popconfirm
                        title="确认删除"
                        description="确定要删除这个模板吗？"
                        onConfirm={() => handleDelete(record.id)}
                        okText="确定"
                        cancelText="取消"
                    >
                        <Button
                            type="primary"
                            danger
                            size="small"
                            icon={<DeleteOutlined />}
                        >
                            删除
                        </Button>
                    </Popconfirm>
                </Space>
            ),
        },
    ]

    const fetchData = async (params = {}) => {
        setLoading(true)
        try {
            const res = await getPromptList({
                ...params,
                current: pagination.current,
                pageSize: pagination.pageSize,
            })
            setData(res.data.data.records)
            setPagination({
                ...pagination,
                total: res.data.total,
            })
        } catch (error) {
            message.error('获取字典列表失败')
        } finally {
            setLoading(false)
        }
    }

    const fetchCategories = async () => {
        try {
            const res = await getCategories()
            // 确保categories是一个数组
            const categoriesList = Array.isArray(res.data.data) ? res.data.data : []
            setCategories(['全部', ...categoriesList])
        } catch (error) {
            message.error('获取分类失败')
            setCategories([])
        }
    }

    const handleDelete = async (id) => {
        try {
            await deleteDict(id)
            message.success('删除成功')
            fetchData(searchParams)
        } catch (error) {
            message.error('删除失败')
        }
    }

    const handleSearch = (values) => {
        setSearchParams(values)
        fetchData(values)
    }

    const handleReset = () => {
        form.resetFields()
        setSearchParams({})
        fetchData()
    }

    const showModal = (dict = null) => {
        setCurrentDict(dict)
        form.setFieldsValue(dict || {
            title: '',
            description: '',
            category: '',
            tags: '',
            content: '',
            templateKeys: ''
        })
        setIsModalOpen(true)
    }

    const handleOk = async () => {
        try {
            const values = await form.validateFields()
            if (currentDict) {
                await updateDict({ ...values, id: currentDict.id })
                message.success('更新成功')
            } else {
                await addDict(values)
                message.success('添加成功')
            }
            setIsModalOpen(false)
            fetchData(searchParams)
        } catch (error) {
            console.error('提交失败:', error)
        }
    }

    const handleCancel = () => {
        setIsModalOpen(false)
    }

    useEffect(() => {
        fetchData()
        fetchCategories()
    }, [pagination.current])

    return (
        <div className="dict-manager">
            <div className="search-bar">
                <Form form={form} onFinish={handleSearch} layout="inline">
                    <Form.Item name="title">
                        <Input placeholder="模板名称" />
                    </Form.Item>
                    <Form.Item name="category">
                        <Select placeholder="分类" style={{ width: 120 }}>
                            {categories && categories.map(category => (
                                <Select.Option key={category} value={category}>
                                    {category}
                                </Select.Option>
                            ))}
                        </Select>
                    </Form.Item>
                    <Space>
                        <Button type="primary" htmlType="submit">搜索</Button>
                        <Button onClick={handleReset}>重置</Button>
                        <Button type="primary" onClick={() => showModal()}>添加模板</Button>
                    </Space>
                </Form>
            </div>
            <Table
                columns={columns}
                dataSource={data}
                rowKey="id"
                loading={loading}
                pagination={pagination}
                onChange={(pagination) => setPagination(pagination)}
            />

            <Modal
                title={currentDict ? '编辑模板' : '添加模板'}
                open={isModalOpen}
                onOk={handleOk}
                onCancel={handleCancel}
                width={800}
            >
                <Form form={form} layout="vertical">
                    <Form.Item
                        name="title"
                        label="模板名称"
                        rules={[{ required: true, message: '请输入模板名称' }]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        name="description"
                        label="描述"
                    >
                        <Input.TextArea />
                    </Form.Item>
                    <Form.Item
                        name="category"
                        label="分类"
                    >
                        <Select>
                            {categories && categories.map(category => (
                                <Select.Option key={category} value={category}>
                                    {category}
                                </Select.Option>
                            ))}
                        </Select>
                    </Form.Item>
                    <Form.Item
                        name="tags"
                        label="标签"
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        name="content"
                        label="内容"
                    >
                        <Input.TextArea rows={6} />
                    </Form.Item>
                    <Form.Item
                        name="templateKeys"
                        label="替换关键词"
                    >
                        <Input.TextArea placeholder="多个关键词用逗号分隔" />
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    )
}

